package cn.szv5.register.server;

/**
 * 应用模块名称<p> 自我保护机制<p> Copyright: Copyright (C) 2022 , Inc. All rights reserved. <p> Company: 阿飞工作室<p>
 *
 * @author Carl
 * @since 2022/2/26 21:30
 */
public class SelfProtectionPolicy {

    private static SelfProtectionPolicy instance = new SelfProtectionPolicy();

    // 期望的一个心跳的次数，如果你有10个实例，这个数值就是10*2=20
    private long expectedHeartbeatRate = 0L;

    // 期望的心跳次数的阈值，10*2*0.85=17,每分钟至少得有17次心跳，才不用进入自我保护机制
    private long expectedHeartbeatThreshold = 0L;

    private SelfProtectionPolicy() {
    }

    /**
     * 是否需要开启自我保护机制
     *
     * @return
     */
    public boolean isEnabled() {
        HeartbeatCounter heartbeatMessuredRate = HeartbeatCounter.getInstance();
        long latestMinuteHeartbeatRate = heartbeatMessuredRate.get();
        if (latestMinuteHeartbeatRate < expectedHeartbeatThreshold) {
            System.out.println(
                "【自我保护机制开启】最近一分钟心跳次数=" + latestMinuteHeartbeatRate + ", 期望心跳次数=" + expectedHeartbeatThreshold);
            return true;
        }
        System.out.println(
            "【自我保护机制未开启】最近一分钟心跳次数=" + latestMinuteHeartbeatRate + ", 期望心跳次数=" + expectedHeartbeatThreshold);
        return false;
    }

    public static SelfProtectionPolicy getInstance() {
        return instance;
    }

    public long getExpectedHeartbeatRate() {
        return expectedHeartbeatRate;
    }

    public void setExpectedHeartbeatRate(long expectedHeartbeatRate) {
        this.expectedHeartbeatRate = expectedHeartbeatRate;
    }

    public long getExpectedHeartbeatThreshold() {
        return expectedHeartbeatThreshold;
    }

    public void setExpectedHeartbeatThreshold(long expectedHeartbeatThreshold) {
        this.expectedHeartbeatThreshold = expectedHeartbeatThreshold;
    }
}
